package com.xuecheng.govern.gateway.service;

import com.xuecheng.framework.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author: gongfy
 * @create: 2020/9/15 9:39
 * @Description: 用户身份校验
 */
@Service
public class AuthService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //1、从cookie查询用户身份令牌是否存在
    public String getTokenFromCookie(HttpServletRequest request){
        Map<String, String> cookieMap = CookieUtil.readCookie(request, "uid");
        String access_token = cookieMap.get("uid");
        if (StringUtils.isEmpty(access_token)){
            return null;
        }
        return access_token;
    }
    //2、从http header查询jwt令牌是否存在
    public String getTokenFromHeader(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)){
            return null;
        }
        if (!authorization.startsWith("Bearer ")){ // 是不是以"Bearer "开头
            return null;
        }
        return authorization;
    }
    //3、从Redis查询user_token令牌是否过期
    public long getExpire(String access_token){ //由于令牌存储时采用 String序列化策略，所以用StringRedisTemplate来查询，使用RedisTemplate无法完成查询
        //组件token在redis中的key
        String key = "user_token" + access_token;
        Long expire = stringRedisTemplate.getExpire(key); // 如果过期 expire -2
        return expire;
    }

}
